//
//  ENPrefsController.m
//  ENPrefs
//
//  Created by Andrew McGeachie on 10/23/07.
//
//  Copyright 2007 EverNote Corporation.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the
//  License. You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0 
//
//  Unless required by applicable law or agreed to in writing,
//  software distributed under the License is distributed on an "AS
//  IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
//  express or implied. See the License for the specific language
//  governing permissions and limitations under the License.
//

#import "ENPrefsController.h"
#import "ENPrefsToolbarItem.h"


@implementation ENPrefsController

@synthesize prefsWindow;


/**
 * DOCME
 */
- (void) toolbarItemClicked: (id) sender
{
  NSWindow * window = self.prefsWindow;
  
  ENPrefsView * prefView = [sender preferenceView];
  if (prefView == nil) {
    NSLog(@"Couldn't find pref view for item labeled '%@'", [sender label]);
    return;
  }
  
  // complete any editing in progress.  if the view refuses then too bad.
  [window setInitialFirstResponder: nil];
  [window makeFirstResponder: nil];
  
  NSView * contentView = [window contentView];
  NSArray * subViews = [contentView subviews];
  // i don't expect there to ever be more than one sub-view...meh
  while ([subViews count] > 0) {
    [[subViews objectAtIndex: 0] removeFromSuperview];
  }
  
  NSRect prefViewFrame = [prefView frame];
  NSRect prefWindowFrame = [window frame];
  
  int32_t heightChange = NSHeight(prefViewFrame) - NSHeight([contentView frame]);
  
  prefWindowFrame.size.width = NSWidth(prefViewFrame);
  prefWindowFrame.size.height += heightChange;
  // keep the window from moving around
  prefWindowFrame.origin.y -= heightChange;
  
  [window setFrame: prefWindowFrame display:YES animate: YES];
  
  [contentView addSubview: prefView];
  
  [window setInitialFirstResponder: [prefView initialFirstResponder]];
  [window makeFirstResponder: [prefView initialFirstResponder]];
}


/**
 * DOCME
 */
- (void) awakeFromNib
{
  // tell all toolbar items to talk to us
  NSToolbar * toolbar = [self.prefsWindow toolbar];
  NSArray * items = [toolbar items];
  for (NSToolbarItem * item in items) {
    [item setTarget: self];
    [item setAction: @selector(toolbarItemClicked:)];
    [item setEnabled: YES];
  }

  // tell the toolbar to talk to us
  [toolbar setDelegate: self];

  // you wouldn't want to hide the toolbar, would you?
  [self.prefsWindow setShowsToolbarButton: NO];

  // select the first toolbar item
  [toolbar setSelectedItemIdentifier: [[items objectAtIndex: 0] itemIdentifier]];
  [self toolbarItemClicked: [items objectAtIndex: 0]];
  
  // listen for NSWindowDidResignKeyNotification so we can finish editing
  [[NSNotificationCenter defaultCenter] addObserver: self
                                           selector: @selector(endPrefsWindowEditing:)
                                               name: NSWindowDidResignKeyNotification
                                             object: self.prefsWindow];
}


// see .h
- (void) show
{
  [self.prefsWindow center];
  [self.prefsWindow makeKeyAndOrderFront: self];
}


/**
 * This technique comes from Marc Charbonneau’s Blog http://blog.downtownsoftwarehouse.com/2006/12/17/end-editing-in-an-nstextfield/
 *
 * Force any field being edited to finish by setting the
 * firstResponder to nothing, then back to the field being edited.
 * PITA.
 */
- (void) endPrefsWindowEditing: (NSNotification *) notification
{  
  NSWindow * w = self.prefsWindow;
  id responder = [w firstResponder];
  
  // If we're dealing with the field editor, the real first responder is
  // its delegate.
  
  if ( (responder != nil) && [responder isKindOfClass:[NSTextView class]] && [(NSTextView*)responder isFieldEditor] ) {
    responder = ( [[responder delegate] isKindOfClass:[NSResponder class]] ) ? [responder delegate] : nil;
  }
  
  BOOL success = [w makeFirstResponder:nil];
  
  // Return first responder status.
  
  if ( success && responder != nil ) {
    [w makeFirstResponder:responder];
  }
}


/**
 * DOCME
 */
- (NSArray *) toolbarSelectableItemIdentifiers: (NSToolbar *) toolbar
{
  // everything!
  NSArray * items = [toolbar items];
  NSMutableArray * result = [NSMutableArray arrayWithCapacity: [items count]];
  for (NSToolbarItem * item in items) {
    [result addObject: [item itemIdentifier]];
  }
  
  return result;
}

@end
